package ws.very.web.tpl

import org.nutz.mvc.Mvcs
import javax.servlet.http.HttpServletRequest

object Http {
  def req = Mvcs.getReq
  def res = Mvcs.getResp
  def reqPath = Mvcs.getRequestPath(req)
  def webRoot = req.getContextPath

}

trait HttpExpand {

  implicit class ReqExpand(req: HttpServletRequest) {
    private val FixesToken = "wsl!fixes"

    private val CssLinksToken = "wsl!css"

    private val JsLinksToken = "wsl!js"

    def apply(attr: String) = req.getAttribute(attr)
    def getOrUpdateAttr[A](attr: String, update: => A) =
      getOrElseAttr(attr, {
        val v = update
        req.setAttribute(attr, v)
        v
      })

    def getOrElseAttr[A](attr: String, els: => A) = Option(req.getAttribute(attr)).getOrElse(els).asInstanceOf[A]
    def pageFixs = {
      ((str: StringBuilder) => {
        def link2Htmls(token: String, typ: String) = {
          import Http._
          import scala.collection.mutable._
          //  println(getOrElse(token, new LinkedHashSet[String]).size)
          getOrElseAttr(token, new LinkedHashSet[String]).foldLeft(new StringBuilder)((oldld, newld) => oldld.append(LoadStatic(newld, typ).buffer))
        }
        def staticLinks = link2Htmls(CssLinksToken, "css") append
          link2Htmls(JsLinksToken, "js")

        // println(str)
        //println("""str.indexOf""" + str.indexOf("""<head>"""))
        val headIndex = str.indexOf("""</title>""")
        if (headIndex > -1)
          str.insert(headIndex + 8, staticLinks)

        str
      }) +: getOrElseAttr(FixesToken, Seq[(StringBuilder => StringBuilder)]())
    }

    private def addLink2Req(token: String, path: String): Unit = {
      import scala.collection.mutable._

      getOrUpdateAttr(token, new LinkedHashSet[String]) += path
      // println("add path " + path + " len=" + getOrUpdateAttr(token, new LinkedHashSet[String]).size)
    }

    def addJsLink(path: String) =
      addLink2Req(JsLinksToken, path)

    def addCssLink(path: String) =
      addLink2Req(CssLinksToken, path)

  }

}

